package valentini.android.strike;

import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;


import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.IBinder;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public class BackgroundService extends Service {

	@SuppressLint("NewApi")
	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {

		//SharedPreferences prefs = this.getSharedPreferences(getPackageName(),
		//		this.MODE_PRIVATE);

		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		
		Utils util = new Utils();
		String todayKey = getPackageName() + "today";
		Date today = Calendar.getInstance().getTime();
		today = util.removeTime(today);
		long lastRun = prefs.getLong(todayKey, 0);

		if ((lastRun < today.getTime()) && isNetworkAvailable()) {
			if (showNotification()) {

				long when = System.currentTimeMillis();
				Notification notification = new Notification(R.drawable.icon, "Scioperi ALert", when);
				
				CharSequence mContentTitle = "Scioperi ALert";
				CharSequence mContentText = "Clicca per vedere gli scioperi di oggi!";

				Intent clickIntent = new Intent(this, TodayStrike.class);
				clickIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP
						| Intent.FLAG_ACTIVITY_CLEAR_TOP);
				PendingIntent contentIntent = PendingIntent.getActivity(this, 0, clickIntent,
						PendingIntent.FLAG_UPDATE_CURRENT);
				notification.setLatestEventInfo(this, mContentTitle, mContentText, contentIntent);

				
				NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
				notification.flags |= Notification.FLAG_AUTO_CANCEL;

				if (prefs.getBoolean(this.getString(R.string.pref_notification_led_key), true)) {
					notification.flags |= Notification.FLAG_SHOW_LIGHTS;
					notification.ledARGB = Color.parseColor(prefs.getString(this
							.getString(R.string.pref_notification_led_color_key), "red"));
					int mLedBlinkRate = Integer.parseInt(prefs.getString(this
							.getString(R.string.pref_notification_led_blink_rate_key), "2"));
					notification.ledOnMS = 500;
					notification.ledOffMS = mLedBlinkRate * 1000;
				}
				
				mNotificationManager.notify(10, notification);

				// inboxStyleNotification();
				Vibrator vibrator = (Vibrator) this
						.getSystemService(this.VIBRATOR_SERVICE);
				vibrator.vibrate(500);
				prefs.edit().putLong(todayKey, today.getTime()).commit();
				// prefs.edit().putBoolean(dateTimeKey, true).commit();
			}
			return Service.START_STICKY;
		} else {
			return Service.START_STICKY;
		}
	}

	@Override
	public IBinder onBind(Intent intent) {

		return null;
	}

	public boolean isNetworkAvailable() {
		ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetworkInfo = connectivityManager
				.getActiveNetworkInfo();
		return activeNetworkInfo != null && activeNetworkInfo.isConnected();
	}

	public void basicNotification() {
		Notification notification = new Notification.Builder(this)
				.setContentTitle("Basic Notification")
				.setContentText("Basic Notification, used earlier")
				.setSmallIcon(android.R.drawable.ic_lock_silent_mode).build();
		notification.flags |= Notification.FLAG_AUTO_CANCEL;
		NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		notificationManager.notify(0, notification);
	}

	public PendingIntent getPendingIntent() {
		return PendingIntent.getActivity(this, 0, new Intent(this,
				TodayStrike.class), 0);
	}

	public boolean showNotification() {

		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(this);
		HtmlParser hp = HtmlParser.getInstance();

		Resources res = getResources();
		TypedArray categories = res.obtainTypedArray(R.array.secotrs);

		Set<String> todayCategories = hp.getTodayStrikeSectors();

		if (todayCategories.isEmpty())
			return false;

		boolean pref = true;

		pref = prefs.getBoolean("pref_notfication_plane", true);
		if (pref && todayCategories.contains(categories.getString(0)))
			return true;

		pref = prefs.getBoolean("pref_notfication_ship", true);
		if (pref && todayCategories.contains(categories.getString(1)))
			return true;

		pref = prefs.getBoolean("pref_notfication_bus", true);
		if (pref && todayCategories.contains(categories.getString(2)))
			return true;

		pref = prefs.getBoolean("pref_notfication_train", true);
		if (pref && todayCategories.contains(categories.getString(3)))
			return true;

		return false;

	}

}
